package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmNewsMatetrialService;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static io.netty.handler.codec.http.multipart.DiskFileUpload.prefix;

@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    FileStorageService fileStorageService;
    @Value("${file.oss.web-site}")
    String webSite;
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //判断数据合法性
        if (multipartFile ==null ||multipartFile.getSize() ==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"请上传一张图片");
        }
        //获取登录UserId
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        String filename = multipartFile.getOriginalFilename();
        if (!checkFileSuffix(filename)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"请上传正确的格式");
        }
        // 2 上传到oss
        String fileId = null;
        try {
            String name = UUID.randomUUID().toString().replace("-", "");
            String suffix = filename.substring(filename.lastIndexOf("."));
            fileId = fileStorageService.store(prefix, filename+suffix, multipartFile.getInputStream());
            log.info("阿里云OSS 文件 fileId: {}",fileId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("阿里云文件上传失败 uploadPicture error: {}", e);
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        // 3 封装数据并保持到素材库中
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setType((short)0);
        wmMaterial.setCreatedTime(new Date());
        // 设置文件id
        wmMaterial.setUrl(fileId);
        wmMaterial.setUserId(user.getId());
        save(wmMaterial);
        // 前端显示
        wmMaterial.setUrl(webSite+fileId);
        // 4 返回结果
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult findList(WmMaterialDTO dto) {
        // 1 参数校验
        dto.checkParam();
        // 2 执行业务查询
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        // 收藏
        if (dto.getIsCollection() != null && dto.getIsCollection() == 1) {
            wrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        // 当前登录用户的素材
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        wrapper.eq(WmMaterial::getUserId, user.getId());
        // 时间倒序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        IPage<WmMaterial> pageParam = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmMaterial> resultPage = page(pageParam, wrapper);
        List<WmMaterial> records = resultPage.getRecords();
        for (WmMaterial record : records) {
            record.setUrl(webSite + record.getUrl());
        }
        // 3 封装结果
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), resultPage.getTotal());
        pageResponseResult.setData(records);
        return pageResponseResult;
    }

    /**
     * 根据图片Id收藏图片
     * @param id
     * @return
     * 未完成
     */
    @Override
    public ResponseResult collect(Integer id) {
        //判断数据合法性
        if (id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //判断图片是否存在
        WmMaterial wmMaterial = this.getById(id);
        if (wmMaterial == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"图片不存在");
        }
        WmMaterial material = getById(id);
        //获取当前用户信息
        Integer uid = WmThreadLocalUtils.getUser().getId();
        if (uid == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //判断是否为当前素材的用户收藏
        if (!uid.equals(wmMaterial.getUserId())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_ALLOW,"只能当前用户收藏");
        }
        //修改根据当前素材
        Short isCollection = wmMaterial.getIsCollection();
        if (isCollection == 0){
            wmMaterial.setIsCollection((short) 1);
        }
        this.updateById(wmMaterial);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 删除图片
     * @param id
     * @return
     */

    @Autowired
    WmNewsMatetrialService wmNewsMatetrialService;
    @Override
    public ResponseResult delPicture(Integer id) {
        //校验数据合法性
        if (id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"id为空");
        }
        //根据id查询当前图片是否存在
        WmMaterial wmMaterial = this.getById(id);
        if (wmMaterial == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"当前图片不存在");
        }
        //判断当前图片是否被引用
        LambdaQueryWrapper<WmNewsMaterial> wrapper = Wrappers.lambdaQuery();
        Map<String, Object> map = wmNewsMatetrialService.getMap(wrapper.eq(WmNewsMaterial::getMaterialId, id));
        if (map != null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_ALLOW,"当前图片已被应用");
        }
        //根据id删除当前图片
        this.removeById(id);
        // 删除图片OSS
        fileStorageService.delete(wmMaterial.getUrl());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 取消收藏
     * @param id
     * @return
     */
    @Override
    public ResponseResult cancelCollect(Integer id) {
        //校验数据合法性
        if (id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //根据id查询素材信息
        WmMaterial wmMaterial = this.getById(id);
        //判断素材是否存在
        if (wmMaterial == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"当前素材不存在");
        }
        //判断状态是否被收藏
        if (wmMaterial.getIsCollection() != 1){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_ALLOW,"当前素材未被收藏");
        }
        //修改状态取消收藏
        wmMaterial.setIsCollection((short) 0);
        this.updateById(wmMaterial);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 检查文件格式 目前仅仅支持jpg  jpeg  png  gif 图片的上传
     * @param path
     * @return
     */
    private boolean checkFileSuffix(String path){
        if(StringUtils.isBlank(path)) return false;
        List<String> allowSuffix = Arrays.asList("jpg", "jpeg", "png", "gif");
        boolean isAllow = false;
        for (String suffix : allowSuffix) {
            if(path.endsWith(suffix)){
                isAllow = true;
                break;
            }
        }
        return isAllow;
    }
}
